package sp.dao;


import sp.entity.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserDaoImpl extends BaseDao<User> implements UserDao {

    @Override
    public Page<User> findByPage(Map<String,String> params, int page, int rows) {
        StringBuffer countSql = new StringBuffer("select count(1) from users where 1=1 and type > 0");
        StringBuffer sql = new StringBuffer("select userId, userName,password,type,role from users where 1=1 and type > 0");
        StringBuffer cond = new StringBuffer();
        List<Object> values = new ArrayList<>();
        if(params!=null&&params.size()>0){
            if(params.containsKey("userId")) {
                cond.append(" and userId = ?");
                values.add(params.get("userId"));
            }

            if(params.containsKey("userName")) {
                cond.append(" and userName like ?");
                values.add(params.get("userName")+"%");
            }
            countSql.append(cond);
            sql.append(cond);
        }
        sql.append(" order by userId limit ?,?");
        return queryByPage(countSql.toString(),sql.toString(),values.toArray(),page,rows);
    }

    @Override
    public List<User> find(User user) {
        StringBuffer sql = new StringBuffer("select userName,type from users where userName =? and password = ?");
        return query(sql.toString(),new Object[]{user.getUserName(),user.getPassword()});
    }

    @Override
    public List<User> findAll() {
        StringBuffer sql = new StringBuffer("select userName from users");
        return query(sql.toString(),new Object[]{});
    }

    @Override
    public void delete(String id) {
        super.executeUpdate("delete from users where userId = ?",new Object[]{id});
    }
}
